/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
 * right(right) {}
 * };
 */
class Solution {
public:
    bool dfs(TreeNode* root, int targetSum) {
        if (root == nullptr)
            return false;
        if (root->left == nullptr && root->right == nullptr &&
            targetSum == root->val)
            return true;
        if (root->left) {
            // 如果左子树找到了一条路径，返回true
            if (dfs(root->left, targetSum - root->val))
                return true;
        }
        if (root->right) {
            // 如果左子树找到了一条路径，返回true
            if (dfs(root->right, targetSum - root->val))
                return true;
        }
        return false;
    }
    bool hasPathSum(TreeNode* root, int targetSum) {
        if (root == nullptr)
            return false;
        if (dfs(root, targetSum))
            return true;
        return false;
    }
};
